<!-- src/views/Login.vue -->
<template>
  <div class="login-container">
    <div class="login-form">
      <h2>可控制的轻量级 VPN 系统</h2>

      <form @submit.prevent="handleLogin">
        <div class="form-group">
          <label>邮箱</label>
          <input
              v-model="form.email"
              type="email"
              placeholder="请输入邮箱"
              required
              :disabled="loading"
          />
        </div>

        <div class="form-group">
          <label>密码</label>
          <input
              v-model="form.password"
              type="password"
              placeholder="请输入密码"
              required
              :disabled="loading"
          />
        </div>

        <!-- 滑块验证码区域 -->
        <div class="captcha-section">
          <h3>安全验证</h3>
          <p>请完成滑块验证以继续登录</p>
          <SliderCaptcha
              ref="captchaRef"
              @verified="onCaptchaVerified"
          />

          <div v-if="captchaError" class="error-message">
            {{ captchaError }}
          </div>
        </div>

        <button
            type="submit"
            :disabled="loading || !form.captchaVerified"
            class="login-btn"
        >
          {{ loading ? '登录中...' : '登录' }}
        </button>
      </form>
    </div>
  </div>
</template>

<!-- 修改 src/views/Login.vue 中的 onCaptchaVerified 方法 -->
<script setup>
import { ref, reactive } from 'vue'
import { useRouter } from 'vue-router'
import { useAuthStore } from '@/store/modules/auth'
import { login } from '@/api/auth'
import SliderCaptcha from '@/components/SliderCaptcha.vue'

const router = useRouter()
const authStore = useAuthStore()
const captchaRef = ref(null)

// 表单数据
const form = reactive({
  email: '',
  password: '',
  captchaVerified: false,
  captchaToken: '',
  userOffset: 0
})

const loading = ref(false)
const captchaError = ref('')

/**
 * 验证码验证成功回调
 */
const onCaptchaVerified = (token) => {
  form.captchaVerified = true
  form.captchaToken = token
  captchaError.value = ''
  console.log('✅ 验证码验证成功')

  // 立即获取滑块位置并存储
  if (captchaRef.value && captchaRef.value.getCurrentPosition) {
    form.userOffset = captchaRef.value.getCurrentPosition()
    console.log('📌 存储滑块位置:', form.userOffset)
  }
}

/**
 * 处理登录
 */
const handleLogin = async () => {
  if (!form.email || !form.password) {
    alert('请填写邮箱和密码')
    return
  }

  if (!form.captchaVerified) {
    captchaError.value = '请先完成安全验证'
    return
  }

  loading.value = true
  captchaError.value = ''

  try {
    console.log('📤 发送登录请求:', {
      email: form.email,
      captcha_token: form.captchaToken,
      user_offset: form.userOffset
    })

    const response = await login({
      email: form.email,
      password: form.password,
      captcha_token: form.captchaToken,
      user_offset: form.userOffset
    })

    if (response.data && response.data.access_token) {
      // 设置 token
      authStore.setToken(response.data.access_token)

      // 等待用户数据加载完成
      await authStore.fetchUserData()

      alert('登录成功！')

      // 确保路由跳转
      router.push('/dashboard').then(() => {
        console.log('✅ 成功跳转到仪表板')
      }).catch(err => {
        console.error('路由跳转失败:', err)
        // 备用跳转方案
        window.location.href = '/dashboard'
      })
    } else {
      throw new Error('登录响应中没有 access_token')
    }
  } catch (error) {
    console.error('登录失败:', error)
    if (error.response?.status === 401) {
      captchaError.value = '邮箱或密码错误'
    } else if (error.response?.status === 422) {
      captchaError.value = '验证码验证失败'
    } else {
      captchaError.value = error.response?.data?.detail || '登录失败，请重试'
    }

    // 刷新验证码
    if (captchaRef.value) {
      captchaRef.value.refreshCaptcha()
    }
    form.captchaVerified = false
    form.userOffset = 0
  } finally {
    loading.value = false
  }
}
</script>

<style scoped>
/* 样式保持不变 */
.login-container {
  min-height: 100vh;
  display: flex;
  align-items: center;
  justify-content: center;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
}

.login-form {
  background: white;
  padding: 40px;
  border-radius: 12px;
  box-shadow: 0 20px 40px rgba(0,0,0,0.1);
  width: 400px;
  max-width: 90%;
}

h2 {
  text-align: center;
  color: #333;
  margin-bottom: 30px;
}

.form-group {
  margin-bottom: 20px;
}

label {
  display: block;
  margin-bottom: 8px;
  color: #555;
}

input {
  width: 100%;
  padding: 12px;
  border: 1px solid #ddd;
  border-radius: 6px;
  font-size: 14px;
}

.captcha-section {
  margin: 20px 0;
  padding: 15px;
  background: #f8f9fa;
  border-radius: 8px;
}

.error-message {
  color: #ff4d4f;
  font-size: 14px;
  margin-top: 10px;
  text-align: center;
}

.login-btn {
  width: 100%;
  padding: 12px;
  background: #1890ff;
  color: white;
  border: none;
  border-radius: 6px;
  font-size: 16px;
  cursor: pointer;
  margin-top: 20px;
}

.login-btn:disabled {
  background: #ccc;
  cursor: not-allowed;
}
</style>